package com.leslie.hhcommunity.service.impl;

import com.leslie.hhcommunity.dao.CommentMapper;
import com.leslie.hhcommunity.dao.DiscussPostMapper;
import com.leslie.hhcommunity.entity.Comment;
import com.leslie.hhcommunity.service.CommentService;
import com.leslie.hhcommunity.util.CommunityConstant;
import com.leslie.hhcommunity.util.SensitiveFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.util.HtmlUtils;

import java.util.List;

/**
 * @author
 * @PackageName:com.leslie.hhcommunity.service.impl
 * @ClassnName:CommentServiceImpl
 * @Description:
 * @Date 2022/1/4  12:07
 */
@Service
public class CommentServiceImpl implements CommentService, CommunityConstant {

	@Autowired
	CommentMapper commentMapper;
	@Autowired
	SensitiveFilter sensitiveFilter;
	@Autowired
	DiscussPostMapper discussPostMapper;
	/**
	 * 分页查询评论
	 *
	 * @param entityType 实体类型
	 * @param entityId   实体id
	 * @param offset
	 * @param limit
	 * @return
	 */
	@Override
	public List<Comment> selectCommentsByEntity(int entityType, int entityId, int offset, int limit) {
		return commentMapper.selectCommentsByEntity(entityType, entityId, offset, limit);
	}

	/**
	 * 查询评论总数
	 *
	 * @param entityType
	 * @param entityId
	 * @return
	 */
	@Override
	public int selectCountByEntity(int entityType, int entityId) {
		return commentMapper.selectCountByEntity(entityType, entityId);
	}

	/**
	 * 添加评论 开启事务
	 * @param comment
	 * @return
	 */
	@Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	@Override
	public int insertComment(Comment comment) {
		if (comment == null){
			throw new IllegalArgumentException("参数不能为空");
		}
		//添加评论
		comment.setContent(HtmlUtils.htmlEscape(comment.getContent()));
		comment.setContent(sensitiveFilter.filter(comment.getContent()));
		int rows = commentMapper.insertComment(comment);

		// 更新帖子评论的数量
		if (comment.getEntityType() == ENTITY_TYPE_POST){
			int count = commentMapper.selectCountByEntity(comment.getEntityType(), comment.getEntityId());
			discussPostMapper.updateCommentCount(comment.getEntityId(), count);
		}
		return rows;
	}

	@Override
	public Comment selectCommentsById(int entityId) {
		return commentMapper.selectCommentsById(entityId);
	}
}
